<?php

namespace app\admin\controller;

use think\Db;
use think\facade\View;
use app\admin\model\SysuserModel;
use app\common\controller\AdminBaseController;
use app\admin\model\SysroleModel;

class SysroleController extends AdminBaseController
{
    public function index()
    {
        return View::fetch();
    }

    public function view()
    {
        $sysroleModel=new SysroleModel();
        $page = input('param.page');
        $pageSize = input('param.pageSize');
        $sysrolelist=$sysroleModel::with("menus")->paginate($pageSize);
        return json($sysrolelist);
    }

    public function add()
    {
        $isPost = $this->request->isPost();
        if ($isPost) {
            $params = input('post.');
            $menuids=input('post.menuIds');
            if(empty($menuids)){
                $this->error("请选择权限！", "", $params);
                exit;
            }
            Db::name('sysrole')->insert($params);
            $roleId = Db::name('sysrole')->getLastInsID();
            Db::name('sysrole_menu')->where('role_id',$roleId)->delete();

            foreach ($menuids as $menuId) {
                $data[]=[
                    'role_id'=>$roleId,
                    'menu_id'=>$menuId,
                ];
            }
            Db::name('sysrole_menu')->insertAll($data);
            $this->success("成功！", "", $params);
        } else {
            return View::fetch();
        }
    }

    public function edit()
    {
        $isPost = $this->request->isPost();
        if ($isPost) {
            $params = input('post.');
            $menuids=input('post.menuIds');
            if(empty($menuids)){
                $this->error("请选择权限！", "", $params);
                exit;
            }
            Db::name('sysrole')->update($params);

            Db::name('sysrole_menu')->where('role_id',$params['id'])->delete();

            foreach ($menuids as $menuId) {
                $data[]=[
                    'role_id'=>$params['id'],
                    'menu_id'=>$menuId,
                ];
            }
            Db::name('sysrole_menu')->insertAll($data);
            $this->success("成功！", "", $params);
        } else {
            $roleid = $this->request->param("id");
            $sysroleModel = new SysroleModel();
            $sysrole = $sysroleModel->find($roleid);
            $this->assign("sysrole", $sysrole);

            $roleMenuList = controller("Widget")->widgetRoleMenuList($roleid);
            $roleMenuList = json_encode($roleMenuList, JSON_UNESCAPED_UNICODE);
            $this->assign("userMenuList", $roleMenuList);
            return View::fetch();
        }
    }

    public function delete()
    {
        $id = input('param.id');
        $sysmodel = new SysroleModel();
        $res = $sysmodel::destroy($id);
        $this->success("成功！", "", $res);
    }

}